/* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved.
   Copyright (c) 2018, Percona and/or its affiliates.
   Copyright (c) 2023, GreatDB Software Co., Ltd.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License, version 2.0,
   as published by the Free Software Foundation.

   This program is also distributed with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have included with MySQL.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License, version 2.0, for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#ifndef _my_sys_h
#define _my_sys_h

/**
  @defgroup MYSYS Mysys - low level utilities for MySQL
  @ingroup Runtime_Environment
  @{
  @file include/my_sys.h Common header for many mysys elements.
  @note Many mysys implementation files now have their own header file.
*/

#include "my_config.h"

#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <limits.h>
#ifdef _WIN32
#include <malloc.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdarg.h>
#include <stdio.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <sys/types.h>
#include <time.h>

#include <atomic>  // error_handler_hook

#include "m_string.h" /* IWYU pragma: keep */
#include "my_compiler.h"
#include "my_compress.h"
#include "my_inttypes.h"
#include "my_loglevel.h"

/* HAVE_PSI_*_INTERFACE */
#include "my_psi_config.h" /* IWYU pragma: keep */

#include "my_sharedlib.h"
#include "mysql/components/services/bits/my_io_bits.h"
#include "mysql/components/services/bits/mysql_cond_bits.h"
#include "mysql/components/services/bits/mysql_mutex_bits.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_file_bits.h"
#include "mysql/components/services/bits/psi_memory_bits.h"
#include "mysql/components/services/bits/psi_stage_bits.h"
#include "sql/stream_cipher.h"

struct CHARSET_INFO;
struct MY_CHARSET_LOADER;

struct PSI_cond_bootstrap;
struct PSI_data_lock_bootstrap;
struct PSI_error_bootstrap;
struct PSI_file_bootstrap;
struct PSI_idle_bootstrap;
struct PSI_mdl_bootstrap;
struct PSI_memory_bootstrap;
struct PSI_mutex_bootstrap;
struct PSI_rwlock_bootstrap;
struct PSI_socket_bootstrap;
struct PSI_stage_bootstrap;
struct PSI_statement_bootstrap;
struct PSI_system_bootstrap;
struct PSI_table_bootstrap;
struct PSI_thread_bootstrap;
struct PSI_transaction_bootstrap;
struct PSI_tls_channel_bootstrap;
struct MEM_ROOT;

#define MY_INIT(name)   \
  {                     \
    my_progname = name; \
    my_init();          \
  }

/**
  Max length of an error message generated by mysys utilities.
  Some mysys functions produce error messages. These mostly go
  to stderr.
  This constant defines the size of the buffer used to format
  the message. It should be kept in sync with MYSQL_ERRMSG_SIZE,
  since sometimes mysys errors are stored in the server diagnostics
  area, and we would like to avoid unexpected truncation.
*/
#define MYSYS_ERRMSG_SIZE (512)
#define MYSYS_STRERROR_SIZE (128)

#define MY_FILE_ERROR ((size_t)-1)

/* General bitmaps for my_func's */
// 1 used to be MY_FFNF which has been removed
#define MY_FNABP 2         /* Fatal if not all bytes read/written */
#define MY_NABP 4          /* Error if not all bytes read/written */
#define MY_FAE 8           /* Fatal if any error */
#define MY_WME 16          /* Write message on error */
#define MY_WAIT_IF_FULL 32 /* Wait and try again if disk full error */
#define MY_IGNORE_BADFD 32 /* my_sync: ignore 'bad descriptor' errors */
#define MY_REPORT_WAITING_IF_FULL 64 /* my_write: set status as waiting */
#define MY_FULL_IO 512 /* For my_read - loop intil I/O is complete */
#define MY_DONT_CHECK_FILESIZE 128  /* Option to init_io_cache() */
#define MY_LINK_WARNING 32          /* my_redel() gives warning if links */
#define MY_COPYTIME 64              /* my_redel() copies time */
#define MY_DELETE_OLD 256           /* my_create_with_symlink() */
#define MY_RESOLVE_LINK 128         /* my_realpath(); Only resolve links */
#define MY_HOLD_ORIGINAL_MODES 128  /* my_copy() holds to file modes */
#define MY_SEEK_NOT_DONE 32         /* my_lock may have to do a seek */
#define MY_DONT_WAIT 64             /* my_lock() don't wait if can't lock */
#define MY_ZEROFILL 32              /* my_malloc(), fill array with zero */
#define MY_ALLOW_ZERO_PTR 64        /* my_realloc() ; zero ptr -> malloc */
#define MY_FREE_ON_ERROR 128        /* my_realloc() ; Free old ptr on error */
#define MY_HOLD_ON_ERROR 256        /* my_realloc() ; Return old ptr on error */
#define MY_DONT_OVERWRITE_FILE 1024 /* my_copy: Don't overwrite file */
#define MY_SYNC 4096                /* my_copy(): sync dst file */

#define MYF_RW MYF(MY_WME + MY_NABP) /* For my_read & my_write */

#define MY_CHECK_ERROR 1    /* Params to my_end; Check open-close */
#define MY_GIVE_INFO 2      /* Give time info about process*/
#define MY_DONT_FREE_DBUG 4 /* Do not call DBUG_END() in my_end() */

/* Flags for my_error() */
#define ME_BELL 4          /* DEPRECATED: Ring bell then printing message */
#define ME_ERRORLOG 64     /* Write the error message to error log */
#define ME_FATALERROR 1024 /* Fatal statement error */

/* Bits in last argument to fn_format */
#define MY_REPLACE_DIR 1     /* replace dir in name with 'dir' */
#define MY_REPLACE_EXT 2     /* replace extension with 'ext' */
#define MY_UNPACK_FILENAME 4 /* Unpack name (~ -> home) */
/* 8 Unused. Previously used for MY_PACK_FILENAME. */
#define MY_RESOLVE_SYMLINKS 16 /* Resolve all symbolic links */
#define MY_RETURN_REAL_PATH 32 /* return full path for file */
#define MY_SAFE_PATH 64        /* Return NULL if too long path */
#define MY_RELATIVE_PATH 128   /* name is relative to 'dir' */
#define MY_APPEND_EXT 256      /* add 'ext' as additional extension*/

/* My seek flags */
#define MY_SEEK_SET 0
#define MY_SEEK_CUR 1
#define MY_SEEK_END 2

/* Some constants */
#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */
#define MY_WAIT_GIVE_USER_A_MESSAGE 10   /* Every 10 times of prev */
#define MIN_COMPRESS_LENGTH 50           /* Don't compress small bl. */
#define DFLT_INIT_HITS 3

/* Internal error numbers (for assembler functions) */
#define MY_ERRNO_EDOM 33
#define MY_ERRNO_ERANGE 34

/* defines when allocating data */
extern void *my_multi_malloc(PSI_memory_key key, myf flags, ...);

/*
  Switch to my_malloc() if the memory block to be allocated is bigger than
  max_alloca_sz.
*/
extern PSI_memory_key key_memory_max_alloca;
#define my_safe_alloca(size, max_alloca_sz)  \
  ((size <= max_alloca_sz) ? my_alloca(size) \
                           : my_malloc(key_memory_max_alloca, size, MYF(0)))
#define my_safe_afree(ptr, size, max_alloca_sz) \
  if (size > max_alloca_sz) my_free(ptr)

#if defined(ENABLED_DEBUG_SYNC)
using DebugSyncCallbackFp = void (*)(const char *, size_t);
extern DebugSyncCallbackFp debug_sync_C_callback_ptr;

#define DEBUG_SYNC_C(_sync_point_name_)                                 \
  do {                                                                  \
    if (debug_sync_C_callback_ptr != NULL)                              \
      (*debug_sync_C_callback_ptr)(STRING_WITH_LEN(_sync_point_name_)); \
  } while (0)
#define DEBUG_SYNC_C_IF_THD(thd, _sync_point_name_)                     \
  do {                                                                  \
    if (debug_sync_C_callback_ptr != NULL && thd)                       \
      (*debug_sync_C_callback_ptr)(STRING_WITH_LEN(_sync_point_name_)); \
  } while (0)
#else
#define DEBUG_SYNC_C(_sync_point_name_)
#define DEBUG_SYNC_C_IF_THD(thd, _sync_point_name_)
#endif /* defined(ENABLED_DEBUG_SYNC) */

#ifdef HAVE_LINUX_LARGE_PAGES
extern uint my_get_large_page_size(void);
#else
#define my_get_large_page_size() (0)
#endif /* HAVE_LINUX_LARGE_PAGES */

#define my_alloca(SZ) alloca((size_t)(SZ))

extern char *home_dir;          /* Home directory for user */
extern const char *my_progname; /* program-name (printed in errors) */

using ErrorHandlerFunctionPointer = void (*)(uint, const char *, myf);
extern std::atomic<ErrorHandlerFunctionPointer> error_handler_hook;
extern void (*local_message_hook)(enum loglevel ll, uint ecode, va_list args);

extern MYSQL_PLUGIN_IMPORT ulong my_thread_stack_size;

/*
  Hooks for reporting execution stage information. The server implementation
  of these will also set THD::current_cond/current_mutex.
  By having hooks, we avoid direct dependencies on server code.
*/
extern void (*enter_cond_hook)(void *opaque_thd, mysql_cond_t *cond,
                               mysql_mutex_t *mutex,
                               const PSI_stage_info *stage,
                               PSI_stage_info *old_stage,
                               const char *src_function, const char *src_file,
                               int src_line);

extern void (*exit_cond_hook)(void *opaque_thd, const PSI_stage_info *stage,
                              const char *src_function, const char *src_file,
                              int src_line);

extern void (*enter_stage_hook)(void *opaque_thd,
                                const PSI_stage_info *new_stage,
                                PSI_stage_info *old_stage,
                                const char *src_function, const char *src_file,
                                int src_line);

/*
  Hook for setting THD waiting_for_disk_space flag.
*/
extern void (*set_waiting_for_disk_space_hook)(void *opaque_thd, bool waiting);
/*
  Hook for checking if the thread has been killed.
*/
extern int (*is_killed_hook)(const void *opaque_thd);

/* charsets */
#define MY_ALL_CHARSETS_SIZE 2048
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info;
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[MY_ALL_CHARSETS_SIZE];
extern CHARSET_INFO compiled_charsets[];

/* statistics */
extern ulong my_tmp_file_created;
extern ulong my_file_opened;
extern ulong my_stream_opened;
extern ulong my_file_total_opened;
extern bool my_init_done;

extern MYSQL_PLUGIN_IMPORT int my_umask; /* Default creation mask  */
extern int my_umask_dir;

extern ulong my_default_record_cache_size;
extern bool my_disable_locking, my_enable_symlinks;

extern const char *charsets_dir;

enum cache_type {
  TYPE_NOT_SET = 0,
  READ_CACHE,
  WRITE_CACHE,
  SEQ_READ_APPEND /* sequential read or append */,
  READ_FIFO,
  READ_NET,
  WRITE_NET
};

enum flush_type {
  FLUSH_KEEP,           /* flush block and keep it in the cache */
  FLUSH_RELEASE,        /* flush block and remove it from the cache */
  FLUSH_IGNORE_CHANGED, /* remove block from the cache */
  /*
    As my_disable_flush_pagecache_blocks is always 0, the following option
    is strictly equivalent to FLUSH_KEEP
  */
  FLUSH_FORCE_WRITE
};

struct DYNAMIC_ARRAY {
  uchar *buffer{nullptr};
  uint elements{0}, max_element{0};
  uint alloc_increment{0};
  uint size_of_element{0};
  PSI_memory_key m_psi_key{PSI_NOT_INSTRUMENTED};
};

struct MY_TMPDIR {
  char **list{nullptr};
  uint cur{0}, max{0};
  mysql_mutex_t mutex;
};

struct DYNAMIC_STRING {
  char *str;
  size_t length, max_length;
};

struct IO_CACHE;
typedef int (*IO_CACHE_CALLBACK)(IO_CACHE *);

struct IO_CACHE_SHARE {
  mysql_mutex_t mutex;      /* To sync on reads into buffer. */
  mysql_cond_t cond;        /* To wait for signals. */
  mysql_cond_t cond_writer; /* For a synchronized writer. */
  /* Offset in file corresponding to the first byte of buffer. */
  my_off_t pos_in_file;
  /* If a synchronized write cache is the source of the data. */
  IO_CACHE *source_cache;
  uchar *buffer;       /* The read buffer. */
  uchar *read_end;     /* Behind last valid byte of buffer. */
  int running_threads; /* threads not in lock. */
  int total_threads;   /* threads sharing the cache. */
  int error;           /* Last error. */
};

struct IO_CACHE /* Used when caching files */
{
  /* Offset in file corresponding to the first byte of uchar* buffer. */
  my_off_t pos_in_file{0};
  /*
    The offset of end of file for READ_CACHE and WRITE_CACHE.
    For SEQ_READ_APPEND it the maximum of the actual end of file and
    the position represented by read_end.
  */
  my_off_t end_of_file{0};
  /* Points to current read position in the buffer */
  uchar *read_pos{nullptr};
  /* the non-inclusive boundary in the buffer for the currently valid read */
  uchar *read_end{nullptr};
  uchar *buffer{nullptr}; /* The read buffer */
  /* Used in ASYNC_IO */
  uchar *request_pos{nullptr};

  /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */
  uchar *write_buffer{nullptr};
  /*
    Only used in SEQ_READ_APPEND, and points to the current read position
    in the write buffer. Note that reads in SEQ_READ_APPEND caches can
    happen from both read buffer (uchar* buffer) and write buffer
    (uchar* write_buffer).
  */
  uchar *append_read_pos{nullptr};
  /* Points to current write position in the write buffer */
  uchar *write_pos{nullptr};
  /* The non-inclusive boundary of the valid write area */
  uchar *write_end{nullptr};

  /*
    Current_pos and current_end are convenience variables used by
    my_b_tell() and other routines that need to know the current offset
    current_pos points to &write_pos, and current_end to &write_end in a
    WRITE_CACHE, and &read_pos and &read_end respectively otherwise
  */
  uchar **current_pos{nullptr}, **current_end{nullptr};

  /*
    The lock is for append buffer used in SEQ_READ_APPEND cache
    need mutex copying from append buffer to read buffer.
  */
  mysql_mutex_t append_buffer_lock;
  /*
    The following is used when several threads are reading the
    same file in parallel. They are synchronized on disk
    accesses reading the cached part of the file asynchronously.
    It should be set to NULL to disable the feature.  Only
    READ_CACHE mode is supported.
  */
  IO_CACHE_SHARE *share{nullptr};

  /*
    A caller will use my_b_read() macro to read from the cache
    if the data is already in cache, it will be simply copied with
    memcpy() and internal variables will be accordinging updated with
    no functions invoked. However, if the data is not fully in the cache,
    my_b_read() will call read_function to fetch the data. read_function
    must never be invoked directly.
  */
  int (*read_function)(IO_CACHE *, uchar *, size_t){nullptr};
  /*
    Same idea as in the case of read_function, except my_b_write() needs to
    be replaced with my_b_append() for a SEQ_READ_APPEND cache
  */
  int (*write_function)(IO_CACHE *, const uchar *, size_t){nullptr};
  /*
    Specifies the type of the cache. Depending on the type of the cache
    certain operations might not be available and yield unpredictable
    results. Details to be documented later
  */
  cache_type type{TYPE_NOT_SET};
  /*
    Callbacks when the actual read I/O happens. These were added and
    are currently used for binary logging of LOAD DATA INFILE - when a
    block is read from the file, we create a block create/append event, and
    when IO_CACHE is closed, we create an end event. These functions could,
    of course be used for other things
  */
  IO_CACHE_CALLBACK pre_read{nullptr};
  IO_CACHE_CALLBACK post_read{nullptr};
  IO_CACHE_CALLBACK pre_close{nullptr};
  /*
    Counts the number of times, when we were forced to use disk. We use it to
    increase the binlog_cache_disk_use and binlog_stmt_cache_disk_use status
    variables.
  */
  ulong disk_writes{0};
  void *arg{nullptr};       /* for use by pre/post_read */
  char *file_name{nullptr}; /* if used with 'open_cached_file' */
  char *dir{nullptr}, *prefix{nullptr};
  File file{-1};                               /* file descriptor */
  PSI_file_key file_key{PSI_NOT_INSTRUMENTED}; /* instrumented file key */

  /*
    seek_not_done is set by my_b_seek() to inform the upcoming read/write
    operation that a seek needs to be performed prior to the actual I/O
    error is 0 if the cache operation was successful, -1 if there was a
    "hard" error, and the actual number of I/O-ed bytes if the read/write was
    partial.
  */
  bool seek_not_done{false};
  int error{0};
  /* buffer_length is memory size allocated for buffer or write_buffer */
  size_t buffer_length{0};
  /* read_length is the same as buffer_length except when we use async io */
  size_t read_length{0};
  myf myflags{0}; /* Flags used to my_read/my_write */
  /*
    alloced_buffer is 1 if the buffer was allocated by init_io_cache() and
    0 if it was supplied by the user.
    Currently READ_NET is the only one that will use a buffer allocated
    somewhere else
  */
  bool alloced_buffer{false};
  // This is an encryptor for encrypting the temporary file of the IO cache.
  Stream_cipher *m_encryptor = nullptr;
  // This is a decryptor for decrypting the temporary file of the IO cache.
  Stream_cipher *m_decryptor = nullptr;
  // Synchronize flushed buffer with disk.
  bool disk_sync{false};
  // Delay in milliseconds after disk synchronization of the flushed buffer.
  // Requires disk_sync = true.
  uint disk_sync_delay{0};
};

typedef int (*qsort2_cmp)(const void *, const void *, const void *);

/*
  Subset of struct stat fields filled by stat/lstat/fstat that uniquely
  identify a file
*/
struct ST_FILE_ID {
  dev_t st_dev;
  ino_t st_ino;
};

typedef void (*my_error_reporter)(enum loglevel level, uint ecode, ...);

extern my_error_reporter my_charset_error_reporter;

/* defines for mf_iocache */
extern PSI_file_key key_file_io_cache;

/* Test if buffer is inited */
inline void my_b_clear(IO_CACHE *info) { info->buffer = nullptr; }

inline bool my_b_inited(const IO_CACHE *info) {
  return info->buffer != nullptr;
}

constexpr int my_b_EOF = INT_MIN;

inline int my_b_read(IO_CACHE *info, uchar *buffer, size_t count) {
  if ((size_t)(info->read_end - info->read_pos) >= count) {
    memcpy(buffer, info->read_pos, count);
    info->read_pos += count;
    return 0;
  }
  return (*info->read_function)(info, buffer, count);
}

inline int my_b_write(IO_CACHE *info, const uchar *buffer, size_t count) {
  if ((size_t)(info->write_end - info->write_pos) >= count) {
    memcpy(info->write_pos, buffer, count);
    info->write_pos += count;
    return 0;
  }
  return (*info->write_function)(info, buffer, count);
}

extern int _my_b_get(IO_CACHE *info);

inline int my_b_get(IO_CACHE *info) {
  if (info->read_pos != info->read_end) {
    info->read_pos++;
    return info->read_pos[-1];
  }
  return _my_b_get(info);
}

MY_NODISCARD
inline my_off_t my_b_tell(const IO_CACHE *info) {
  return info->pos_in_file + *info->current_pos - info->request_pos;
}

MY_NODISCARD
inline uchar *my_b_get_buffer_start(const IO_CACHE *info) {
  return info->request_pos;
}

MY_NODISCARD
inline size_t my_b_get_bytes_in_buffer(const IO_CACHE *info) {
  return info->read_end - my_b_get_buffer_start(info);
}

MY_NODISCARD
inline my_off_t my_b_get_pos_in_file(const IO_CACHE *info) {
  return info->pos_in_file;
}

/* tell write offset in the SEQ_APPEND cache */
int my_b_copy_to_file(IO_CACHE *cache, FILE *file);

MY_NODISCARD
inline size_t my_b_bytes_in_cache(const IO_CACHE *info) {
  return *info->current_end - *info->current_pos;
}

/*
  How much overhead does malloc have. The code often allocates
  something like 1024-MALLOC_OVERHEAD bytes
*/
#define MALLOC_OVERHEAD 8

/* Typical record cache */
#define RECORD_CACHE_SIZE (uint)(64 * 1024 - MALLOC_OVERHEAD)

/** struct for once_alloc (block) */
struct USED_MEM {
  USED_MEM *next;    /**< Next block in use */
  unsigned int left; /**< memory left in block  */
  unsigned int size; /**< size of block */
};

/* Prototypes for mysys and my_func functions */

extern int my_copy(const char *from, const char *to, myf MyFlags);
extern int my_delete(const char *name, myf MyFlags);
extern int my_getwd(char *buf, size_t size, myf MyFlags);
extern int my_setwd(const char *dir, myf MyFlags);
extern void *my_once_alloc(size_t Size, myf MyFlags);
extern void my_once_free(void);
extern char *my_once_strdup(const char *src, myf myflags);
extern void *my_once_memdup(const void *src, size_t len, myf myflags);
extern File my_open(const char *FileName, int Flags, myf MyFlags);
#ifndef __WIN__
extern File my_unix_socket_connect(const char *FileName, myf MyFlags) noexcept;
#endif
extern File my_create(const char *FileName, int CreateFlags, int AccessFlags,
                      myf MyFlags);
extern int my_close(File fd, myf MyFlags);
extern int my_mkdir(const char *dir, int Flags, myf MyFlags);
extern int my_readlink(char *to, const char *filename, myf MyFlags);
extern int my_is_symlink(const char *filename, ST_FILE_ID *file_id);
extern int my_realpath(char *to, const char *filename, myf MyFlags);
extern int my_is_same_file(File file, const ST_FILE_ID *file_id);
extern File my_create_with_symlink(const char *linkname, const char *filename,
                                   int createflags, int access_flags,
                                   myf MyFlags);
extern int my_delete_with_symlink(const char *name, myf MyFlags);
extern int my_rename_with_symlink(const char *from, const char *to,
                                  myf MyFlags);
#ifndef _WIN32
extern int my_symlink(const char *content, const char *linkname, myf MyFlags);
#endif
extern size_t my_read(File Filedes, uchar *Buffer, size_t Count, myf MyFlags);
extern size_t my_pread(File Filedes, uchar *Buffer, size_t Count,
                       my_off_t offset, myf MyFlags);
extern int my_rename(const char *from, const char *to, myf MyFlags);
extern my_off_t my_seek(File fd, my_off_t pos, int whence, myf MyFlags);
extern my_off_t my_tell(File fd, myf MyFlags);
extern size_t my_write(File Filedes, const uchar *Buffer, size_t Count,
                       myf MyFlags);
extern size_t my_pwrite(File Filedes, const uchar *Buffer, size_t Count,
                        my_off_t offset, myf MyFlags);
extern size_t my_fread(FILE *stream, uchar *Buffer, size_t Count, myf MyFlags);
extern size_t my_fwrite(FILE *stream, const uchar *Buffer, size_t Count,
                        myf MyFlags);
extern my_off_t my_fseek(FILE *stream, my_off_t pos, int whence);
extern my_off_t my_ftell(FILE *stream);
#if !defined(HAVE_MEMSET_S)
void memset_s(void *dest, size_t dest_max, int c, size_t n);
#endif

/* implemented in my_syslog.c */

// Maximum size of message  that will be logged.
#define MAX_SYSLOG_MESSAGE_SIZE 1024

/* Platform-independent SysLog support */
enum my_syslog_options { MY_SYSLOG_PIDS = 1 };

extern int my_openlog(const char *eventSourceName, int option, int facility);
extern int my_closelog();
extern int my_syslog(const CHARSET_INFO *cs, enum loglevel level,
                     const char *msg);

#ifdef _WIN32
extern int my_access(const char *path, int amode);
#else
#define my_access access
#endif

extern int check_if_legal_filename(const char *path);
extern int check_if_legal_tablename(const char *path);

#ifdef _WIN32
extern bool is_filename_allowed(const char *name, size_t length,
                                bool allow_current_dir);
#else /* _WIN32 */
#define is_filename_allowed(name, length, allow_cwd) (true)
#endif /* _WIN32 */

#ifdef _WIN32
extern int nt_share_delete(const char *name, myf MyFlags);
#define my_delete_allow_opened(fname, flags) nt_share_delete((fname), (flags))
#else
#define my_delete_allow_opened(fname, flags) my_delete((fname), (flags))
#endif

#ifdef _WIN32
/* Windows-only functions (CRT equivalents)*/
extern HANDLE my_get_osfhandle(File fd);
extern void my_osmaperr(unsigned long last_error);
#endif

extern const char *get_global_errmsg(int nr);
extern void wait_for_free_space(const char *filename, int errors);
extern FILE *my_fopen(const char *filename, int Flags, myf MyFlags);
extern FILE *my_fdopen(File fd, const char *filename, int Flags, myf MyFlags);
extern FILE *my_freopen(const char *filename, const char *mode, FILE *stream);
extern int my_fclose(FILE *stream, myf MyFlags);
extern File my_fileno(FILE *stream);
extern int my_chsize(File fd, my_off_t newlength, int filler, myf MyFlags);
extern int my_fallocator(File fd, my_off_t newlength, int filler, myf MyFlags);
extern void thr_set_sync_wait_callback(void (*before_sync)(void),
                                       void (*after_sync)(void));
extern int my_sync(File fd, myf my_flags);
extern char *my_strerror(char *buf, size_t len, int errnum);
extern const char *my_get_err_msg(int nr);
extern void my_error(int nr, myf MyFlags, ...);
extern void my_printf_error(uint my_err, const char *format, myf MyFlags, ...)
    MY_ATTRIBUTE((format(printf, 2, 4)));
extern void my_printv_error(uint error, const char *format, myf MyFlags,
                            va_list ap) MY_ATTRIBUTE((format(printf, 2, 0)));
extern int my_error_register(const char *(*get_errmsg)(int), int first,
                             int last);
extern bool my_error_unregister(int first, int last);
extern void my_message(uint my_err, const char *str, myf MyFlags);
extern void my_message_stderr(uint my_err, const char *str, myf MyFlags);
void my_message_local_stderr(enum loglevel, uint ecode, va_list args);
extern void my_message_local(enum loglevel ll, uint ecode, ...);

/**
  Convenience wrapper for OS error messages which report
  errno/my_errno with %d followed by strerror as %s, as the last
  conversions in the error message.

  The OS error message (my_errno) is formatted in a stack buffer and
  the errno value and a pointer to the buffer is added to the end of
  the parameter pack passed to my_error().

  @param errno_val errno/my_errno number.
  @param ppck parameter pack of additional arguments to pass to my_error().
 */
template <class... Ts>
inline void MyOsError(int errno_val, Ts... ppck) {
  char errbuf[MYSYS_STRERROR_SIZE];
  my_error(ppck..., errno_val, my_strerror(errbuf, sizeof(errbuf), errno_val));
}

extern bool my_init(void);
extern void my_end(int infoflag);
extern const char *my_filename(File fd);
extern MY_MODE get_file_perm(ulong perm_flags);
extern bool my_chmod(const char *filename, ulong perm_flags, myf my_flags);

extern bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist);
extern char *my_tmpdir(MY_TMPDIR *tmpdir);
extern void free_tmpdir(MY_TMPDIR *tmpdir);

extern size_t dirname_part(char *to, const char *name, size_t *to_res_length);
extern size_t dirname_length(const char *name);
#define base_name(A) (A + dirname_length(A))
extern int test_if_hard_path(const char *dir_name);
extern bool has_path(const char *name);
extern char *convert_dirname(char *to, const char *from, const char *from_end);
extern void to_unix_path(char *name);
extern char *fn_ext(char *name);
extern const char *fn_ext(const char *name);
extern char *fn_same(char *toname, const char *name, int flag);
extern char *fn_format(char *to, const char *name, const char *dir,
                       const char *form, uint flag);
extern size_t strlength(const char *str);
extern size_t normalize_dirname(char *to, const char *from);
extern size_t unpack_dirname(char *to, const char *from);
extern size_t cleanup_dirname(char *to, const char *from);
extern size_t system_filename(char *to, const char *from);
extern size_t unpack_filename(char *to, const char *from);
extern char *intern_filename(char *to, const char *from);
extern char *my_path(char *to, const char *progname,
                     const char *own_pathname_part);
extern char *my_load_path(char *to, const char *path,
                          const char *own_path_prefix);
extern bool array_append_string_unique(const char *str, const char **array,
                                       size_t size);

void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos);
my_off_t my_get_ptr(uchar *ptr, size_t pack_length);
MY_NODISCARD
extern int init_io_cache_ext(IO_CACHE *info, File file, size_t cachesize,
                             enum cache_type type, my_off_t seek_offset,
                             bool use_async_io, myf cache_myflags,
                             PSI_file_key file_key);
MY_NODISCARD
extern int init_io_cache(IO_CACHE *info, File file, size_t cachesize,
                         enum cache_type type, my_off_t seek_offset,
                         bool use_async_io, myf cache_myflags);
MY_NODISCARD
extern bool reinit_io_cache(IO_CACHE *info, enum cache_type type,
                            my_off_t seek_offset, bool use_async_io,
                            bool clear_cache);
extern void setup_io_cache(IO_CACHE *info);
/* add for parallel load */
extern void move_io_cache(IO_CACHE *to, IO_CACHE *from);
MY_NODISCARD
extern int _my_b_read(IO_CACHE *info, uchar *Buffer, size_t Count);
MY_NODISCARD
extern int _my_b_read_r(IO_CACHE *info, uchar *Buffer, size_t Count);
extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare,
                                IO_CACHE *write_cache, uint num_threads);
extern void remove_io_thread(IO_CACHE *info);
MY_NODISCARD
extern int _my_b_seq_read(IO_CACHE *info, uchar *Buffer, size_t Count);
extern int _my_b_net_read(IO_CACHE *info, uchar *Buffer, size_t Count);
MY_NODISCARD
extern int _my_b_write(IO_CACHE *info, const uchar *Buffer, size_t Count);
extern int my_b_append(IO_CACHE *info, const uchar *Buffer, size_t Count);
extern int my_b_safe_write(IO_CACHE *info, const uchar *Buffer, size_t Count);

extern int my_block_write(IO_CACHE *info, const uchar *Buffer, size_t Count,
                          my_off_t pos);
extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock);

#define flush_io_cache(info) my_b_flush_io_cache((info), 1)

extern int end_io_cache(IO_CACHE *info);
extern size_t my_b_fill(IO_CACHE *info);
extern void my_b_seek(IO_CACHE *info, my_off_t pos);
extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length);
extern my_off_t my_b_filelength(IO_CACHE *info);
extern size_t my_b_printf(IO_CACHE *info, const char *fmt, ...)
    MY_ATTRIBUTE((format(printf, 2, 3)));
extern size_t my_b_vprintf(IO_CACHE *info, const char *fmt, va_list ap);
extern bool open_cached_file(IO_CACHE *cache, const char *dir,
                             const char *prefix, size_t cache_size,
                             myf cache_myflags);
extern bool open_cached_file_encrypted(IO_CACHE *cache, const char *dir,
                                       const char *prefix, size_t cache_size,
                                       myf cache_myflags, bool encrypted);
extern bool real_open_cached_file(IO_CACHE *cache);
extern void close_cached_file(IO_CACHE *cache);

enum UnlinkOrKeepFile { UNLINK_FILE, KEEP_FILE };
#ifdef WIN32
// Maximum temporary filename length is 3 chars for prefix + 16 chars for base
// 32 encoded UUID (excluding MAC address)
const size_t MY_MAX_TEMP_FILENAME_LEN = 19;
#endif
File create_temp_file(char *to, const char *dir, const char *pfx, int mode,
                      UnlinkOrKeepFile unlink_or_keep, myf MyFlags);

// Use Prealloced_array or std::vector or something similar in C++
extern bool my_init_dynamic_array(DYNAMIC_ARRAY *array, PSI_memory_key key,
                                  uint element_size, void *init_buffer,
                                  uint init_alloc, uint alloc_increment);
/* init_dynamic_array() function is deprecated */

#define dynamic_element(array, array_index, type) \
  ((type)((array)->buffer) + (array_index))

/* Some functions are still in use in C++, because HASH uses DYNAMIC_ARRAY */
extern bool insert_dynamic(DYNAMIC_ARRAY *array, const void *element);
extern void *alloc_dynamic(DYNAMIC_ARRAY *array);
extern void delete_dynamic(DYNAMIC_ARRAY *array);

extern bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str,
                                size_t init_alloc);
extern bool dynstr_append(DYNAMIC_STRING *str, const char *append);
bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append, size_t length);
extern bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append,
                                    ...);
extern bool dynstr_append_quoted(DYNAMIC_STRING *str, const char *quote_str,
                                 const uint quote_len, const char *append, ...);
extern bool dynstr_set(DYNAMIC_STRING *str, const char *init_str);
extern bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size);
extern bool dynstr_trunc(DYNAMIC_STRING *str, size_t n);
extern void dynstr_free(DYNAMIC_STRING *str);
#define alloc_root_inited(A) ((A)->inited())
extern void *multi_alloc_root(MEM_ROOT *mem_root, ...);
extern char *strdup_root(MEM_ROOT *root, const char *str);
extern char *safe_strdup_root(MEM_ROOT *root, const char *str);
extern char *strmake_root(MEM_ROOT *root, const char *str, size_t len);
extern void *memdup_root(MEM_ROOT *root, const void *str, size_t len);
extern bool my_compress(mysql_compress_context *, uchar *, size_t *, size_t *);
extern bool my_uncompress(mysql_compress_context *, uchar *, size_t, size_t *);
extern uchar *my_compress_alloc(mysql_compress_context *comp_ctx,
                                const uchar *packet, size_t *len,
                                size_t *complen);

extern uint my_set_max_open_files(uint files);

extern bool my_gethwaddr(uchar *to);

#define my_microsecond_getsystime() (my_getsystime() / 10)

#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>

#ifndef MAP_NOSYNC
#define MAP_NOSYNC 0
#endif

/*
  Not defined in FreeBSD 11.
  Was never implemented in FreeBSD, so we just set it to 0.
*/
#ifndef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

#ifdef HAVE_MMAP64
#define my_mmap(a, b, c, d, e, f) mmap64(a, b, c, d, e, f)
#else
#define my_mmap(a, b, c, d, e, f) mmap(a, b, c, d, e, f)
#endif
#define my_munmap(a, b) munmap((a), (b))

#else
/* not a complete set of mmap() flags, but only those that nesessary */
#define PROT_READ 1
#define PROT_WRITE 2
#define MAP_NORESERVE 0
#define MAP_SHARED 0x0001
#define MAP_PRIVATE 0x0002
#define MAP_NOSYNC 0x0800
#define MAP_FAILED ((void *)-1)
#define MS_SYNC 0x0000

void *my_mmap(void *, size_t, int, int, int, my_off_t);
int my_munmap(void *, size_t);
#endif

/* my_getpagesize */
static inline int my_getpagesize() {
#ifndef _WIN32
  return getpagesize();
#else
  SYSTEM_INFO si;
  GetSystemInfo(&si);
  return (int)si.dwPageSize;
#endif
}

int my_msync(int, void *, size_t, int);

/* character sets */
extern uint get_charset_number(const char *cs_name, uint cs_flags);
extern uint get_collation_number(const char *name);
extern const char *get_collation_name(uint cs_number);

extern CHARSET_INFO *get_charset(uint cs_number, myf flags);
extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags);
extern CHARSET_INFO *my_collation_get_by_name(MY_CHARSET_LOADER *loader,
                                              const char *name, myf flags);
extern CHARSET_INFO *get_charset_by_csname(const char *cs_name, uint cs_flags,
                                           myf my_flags);
extern CHARSET_INFO *my_charset_get_by_name(MY_CHARSET_LOADER *loader,
                                            const char *name, uint cs_flags,
                                            myf my_flags);
extern bool resolve_charset(const char *cs_name, const CHARSET_INFO *default_cs,
                            const CHARSET_INFO **cs);
extern bool resolve_collation(const char *cl_name,
                              const CHARSET_INFO *default_cl,
                              const CHARSET_INFO **cl);
extern char *get_charsets_dir(char *buf);
extern bool my_charset_same(const CHARSET_INFO *cs1, const CHARSET_INFO *cs2);
extern bool init_compiled_charsets(myf flags);
extern void add_compiled_collation(CHARSET_INFO *cs);
extern size_t escape_string_for_mysql(const CHARSET_INFO *charset_info,
                                      char *to, size_t to_length,
                                      const char *from, size_t length);
extern void charset_uninit();
#ifdef _WIN32
/* File system character set */
extern CHARSET_INFO *fs_character_set(void);
#endif
extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info, char *to,
                                      size_t to_length, const char *from,
                                      size_t length, char quote);
#ifdef _WIN32
extern bool have_tcpip; /* Is set if tcpip is used */

/* implemented in my_windac.c */

int my_security_attr_create(SECURITY_ATTRIBUTES **psa, const char **perror,
                            DWORD owner_rights, DWORD everybody_rights);

void my_security_attr_free(SECURITY_ATTRIBUTES *sa);

/* implemented in my_conio.c */
bool my_win_is_console(FILE *file);
char *my_win_console_readline(const CHARSET_INFO *cs, char *mbbuf,
                              size_t mbbufsize, size_t *nread);
void my_win_console_write(const CHARSET_INFO *cs, const char *data,
                          size_t datalen);
void my_win_console_fputs(const CHARSET_INFO *cs, const char *data);
void my_win_console_putc(const CHARSET_INFO *cs, int c);
void my_win_console_vfprintf(const CHARSET_INFO *cs, const char *fmt,
                             va_list args);
int my_win_translate_command_line_args(const CHARSET_INFO *cs, int *ac,
                                       char ***av);
#endif /* _WIN32 */

#ifdef HAVE_PSI_INTERFACE
void my_init_mysys_psi_keys(void);

extern MYSQL_PLUGIN_IMPORT PSI_cond_bootstrap *psi_cond_hook;
extern void set_psi_cond_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_data_lock_bootstrap *psi_data_lock_hook;
extern void set_psi_data_lock_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_error_bootstrap *psi_error_hook;
extern void set_psi_error_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_file_bootstrap *psi_file_hook;
extern void set_psi_file_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_idle_bootstrap *psi_idle_hook;
extern void set_psi_idle_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_mdl_bootstrap *psi_mdl_hook;
extern void set_psi_mdl_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_memory_bootstrap *psi_memory_hook;
extern void set_psi_memory_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_mutex_bootstrap *psi_mutex_hook;
extern void set_psi_mutex_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_rwlock_bootstrap *psi_rwlock_hook;
extern void set_psi_rwlock_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_socket_bootstrap *psi_socket_hook;
extern void set_psi_socket_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_stage_bootstrap *psi_stage_hook;
extern void set_psi_stage_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_statement_bootstrap *psi_statement_hook;
extern void set_psi_statement_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_system_bootstrap *psi_system_hook;
extern void set_psi_system_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_table_bootstrap *psi_table_hook;
extern void set_psi_table_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_thread_bootstrap *psi_thread_hook;
extern void set_psi_thread_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_transaction_bootstrap *psi_transaction_hook;
extern void set_psi_transaction_service(void *psi);
extern MYSQL_PLUGIN_IMPORT PSI_tls_channel_bootstrap *psi_tls_channel_hook;
extern void set_psi_tls_channel_service(void *psi);
#endif /* HAVE_PSI_INTERFACE */

/**
  @} (end of group MYSYS)
*/

// True if the temporary file of binlog cache is encrypted.
#ifndef NDEBUG
extern bool binlog_cache_temporary_file_is_encrypted;
#endif

/**
  This is a wrapper around mysql_file_seek. Seek to a position in the
  temporary file of a binlog cache, and set the encryption/decryption
  stream offset if binlog_encryption is on.

  @param cache The handler of a binlog cache to seek.
  @param pos The expected position (absolute or relative)
  @param whence A direction parameter and one of
                {SEEK_SET, SEEK_CUR, SEEK_END}
  @param flags  The bitmap of different flags
                MY_WME | MY_FAE | MY_NABP | MY_FNABP |
                MY_DONT_CHECK_FILESIZE and so on.

  @retval The new position in the file, or MY_FILEPOS_ERROR on error.
*/
my_off_t mysql_encryption_file_seek(IO_CACHE *cache, my_off_t pos, int whence,
                                    myf flags);
/**
   This is a wrapper around mysql_file_read. Read data from the temporary
   file of a binlog cache, and take care of decrypting the data if
   binlog_encryption is on.


   @param cache The handler of a binlog cache to read.
   @param[out] buffer The memory buffer to write to.
   @param count The length of data in the temporary file to be read in bytes.
   @param flags The bitmap of different flags
                MY_WME | MY_FAE | MY_NABP | MY_FNABP |
                MY_DONT_CHECK_FILESIZE and so on.

   @retval The length of bytes to be read, or MY_FILE_ERROR on error.
*/
size_t mysql_encryption_file_read(IO_CACHE *cache, uchar *buffer, size_t count,
                                  myf flags);
/**
   This is a wrapper around mysql_file_write. Write data in buffer to the
   temporary file of a binlog cache, and take care of encrypting the data
   if binlog_encryption is on.

   @param cache The handler of a binlog cache to write.
   @param buffer The memory buffer to write from.
   @param count The length of data in buffer to be written in bytes.
   @param flags The bitmap of different flags
                MY_WME | MY_FAE | MY_NABP | MY_FNABP |
                MY_DONT_CHECK_FILESIZE and so on

   @return The number of bytes written
*/
size_t mysql_encryption_file_write(IO_CACHE *cache, const uchar *buffer,
                                   size_t count, myf flags);

/**
   This is a wrapper around mysql_file_pread. Read data from the specified
   offset in a file and take care of decrypting the data if encryption is on.

   @param cache The handler of a file cache to read.
   @param[out] buffer The memory buffer to write to.
   @param count The length of data in the file to be read in bytes.
   @param offset The offset in the file to read from.
   @param flags The bitmap of different flags
                MY_WME | MY_FAE | MY_NABP | MY_FNABP |
                MY_DONT_CHECK_FILESIZE and so on.

   if (flags & (MY_NABP | MY_FNABP)) {
     @retval 0 if count == 0
     @retval 0 success
     @retval MY_FILE_ERROR error
   } else {
     @retval 0 if count == 0
     @retval The number of bytes read.
     @retval MY_FILE_ERROR error
   }
*/

size_t mysql_encryption_file_pread(IO_CACHE *cache, uchar *buffer, size_t count,
                                   my_off_t offset, myf flags);

#endif /* _my_sys_h */
